package com.tzxs.pay.main.bill.detail.refund;

import android.app.Activity;
import android.app.ProgressDialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.tzxs.pay.R;
import com.tzxs.pay.databinding.ActivityRefundBinding;
import com.tzxs.pay.main.base.BaseActivity;
import com.tzxs.pay.main.bill.detail.CollAndInstallDetailActivity;
import com.tzxs.pay.main.bill.detail.model.BankRefundBean;
import com.tzxs.pay.main.bill.detail.model.MsgRefundBean;
import com.tzxs.pay.main.bill.detail.model.RefundBean;
import com.tzxs.pay.main.bill.detail.navigator.MsgRefundNavigator;
import com.tzxs.pay.main.bill.detail.view.RefundDialogFragment;
import com.tzxs.pay.main.bill.viewmodel.BillViewModel;
import com.tzxs.pay.main.gather.viewmodel.BankViewModel;
import com.tzxs.pay.main.login.LoginViewModel;
import com.tzxs.pay.main.mine.PasswordChangeActivity;
import com.tzxs.pay.main.print.utils.print.AidlUtil;
import com.tzxs.pay.util.ISharedPreference;
import com.tzxs.pay.util.StatusBarColorSetter;
import com.tzxs.pay.util.SystemUtil;
import com.tzxs.pay.util.ViewDialog;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 退款页面
 */
public class RefundActivity extends BaseActivity<ActivityRefundBinding> implements MsgRefundNavigator {
    private static final String TAG = RefundActivity.class.getSimpleName();
    private BillViewModel model;
    private BankViewModel bankViewModel;
    private RefundDialogFragment dialogFragment;//验证码退款dialog
    private String orderId;
    private static final int BANK_CODE = 102;//银行卡退款  调起支付页面
    private LoginViewModel loginViewModel;
    private ProgressDialog dialog;

    @Override
    protected Activity getChildActivity() {
        return this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_refund;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarColorSetter.setStatusBarColor(this, Color.parseColor("#FAFAFA"));
        model = ViewModelProviders.of(this).get(BillViewModel.class);
        loginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
        bankViewModel = ViewModelProviders.of(this).get(BankViewModel.class);
        dataBinding.rdToolbar.setTitle("");
        setSupportActionBar(dataBinding.rdToolbar);
        //初始化打印机
        AidlUtil.getInstance().initPrinter();
        orderId = getIntent().getStringExtra("orderId");
        dataBinding.rdToolbar.setNavigationOnClickListener(v -> onBackPressed());
        model.snackbarText.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                if (s != null) {
                    Snackbar.make(dataBinding.rdToolbar, s, Snackbar.LENGTH_SHORT).show();
                }
            }
        });
        dataBinding.refundSetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RefundActivity.this, PasswordChangeActivity.class);
                startActivity(intent);
            }
        });
        loginViewModel.snackbarEvent.observe(this, s -> {
            if (s != null) {
                Toast.makeText(RefundActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        });
        model.dialogText.observe(this, s -> {
            if (s == null) {
                dialog.dismiss();
            } else {
                dialog = ProgressDialog.show(RefundActivity.this, s, "请稍等……", false, false);
            }
        });
        dataBinding.applyRefund.setOnClickListener(v -> {
            if (TextUtils.isEmpty(dataBinding.refundAmount.getText().toString())) {
                Snackbar.make(dataBinding.rdToolbar, "请输入退款金额", Snackbar.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(dataBinding.refundPassword.getText().toString())) {
                Snackbar.make(dataBinding.rdToolbar, "请输入支付密码", Snackbar.LENGTH_SHORT).show();
                return;
            }


            showRefundDialog(orderId, dataBinding.refundNote.getText().toString(),
                    dataBinding.refundPassword.getText().toString(),
                    dataBinding.refundAmount.getText().toString());
        });
    }

    /**
     * 退款dialog
     *
     * @param orderId  订单号
     * @param bz       备注
     * @param password 支付密码
     * @param amount   金额
     */
    private void showRefundDialog(String orderId, String bz, String password, String amount ) {
        model.verifyOrder(orderId, () -> {
            if (model.orderStatus.get() == 1) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this)
                        .setTitle("提示!")
                        .setMessage("请确认退款金额是否正确?,一旦操作,资金将无法被追回,请谨慎操作!")
                        .setPositiveButton("确认", (DialogInterface dialog, int which) -> {
                            startRefund(orderId, bz, password, amount);
                            dialog.dismiss();
                        }).setNegativeButton("取消", (dialog, which) -> {
                            dialog.dismiss();
                        });
                builder.show();
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("backMoney", amount);
                dialogFragment = RefundDialogFragment.newInstance();
                dialogFragment.setArguments(bundle);
                dialogFragment.setCancelable(false);
                dialogFragment.show(getSupportFragmentManager(), RefundDialogFragment.TAG);
            }
        });
    }

    //将交易金额统一处理成12位，不足12位的在前面补0
    private String getAmount(String amount) {
        if (TextUtils.isEmpty(amount)) return null;
        while (amount.length() < 12) {
            amount = "0" + amount;
        }
        return amount;
    }

    //开始退款
    private void startRefund(String orderId, String bz, String password, String amount) {
        if (orderId.startsWith("bk")) {//银行卡退款
            bankViewModel.bankRefundOrCreate(Float.parseFloat(amount), password, bz, orderId, () -> {
                //银行卡退款订单创建成功
                if (bankViewModel.bankRefund.get() != null) {
                    BankRefundBean.DataBean bean = bankViewModel.bankRefund.get();
                    float du = Float.valueOf(bean.getAmount()) * 100;
                    Log.d(TAG, "getInfo: 金额double:" + du);
                    float tradeMoney = Math.round(du);
                    int result = (int) tradeMoney;
                    Intent intent = new Intent();
                    intent.setComponent(new ComponentName("com.shengpay.smartpos.shengpaysdk", "com.shengpay.smartpos.shengpaysdk.activity.MainActivity"));
                    intent.putExtra("appId", getPackageName());
                    intent.putExtra("amount", getAmount(String.valueOf(result)));//交易金额
                    intent.putExtra("orderNoSFT", bean.getOut_trade_no());//交易订单号
                    intent.putExtra("orderInfo", bean.getOut_trade_no());//订单信息
                    intent.putExtra("transName", "1");//退款
                    intent.putExtra("oldTraceNo", bean.getTraceNo());

                    //intent.putExtra("transName", "1");//退款
                    //用户联备注
                    intent.putExtra("printMerchantInfo",
                            "交易订单号:" + bean.getOut_trade_no() + "        "
                                    + "\n交易备注: 银行卡退款");
                    intent.putExtra("printMerchantInfo2", orderId);
                    intent.putExtra("priInfo", "交易订单号:" + bean.getOut_trade_no() + "        "
                            + "\n交易备注:  银行卡退款");
                    intent.putExtra("priInfo2", orderId);
                    //开始银行卡退款
                    if (isInstallShengfuPay()) {
                        startActivityForResult(intent, BANK_CODE);
                    } else {
                        Toast.makeText(this, "请前往应用市场下载盛付通支付!", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {//普通订单退款
            model.refund(orderId, bz, password, amount, () -> {
                print(model.refundBean.get());
                showPrintDialog(model.refundBean.get());
            });
        }
    }

    //显示打印dialog
    private void showPrintDialog(Object bean) {
        ViewDialog viewDialog = new ViewDialog();
        viewDialog.setLayoutId(R.layout.print_dialog);
        viewDialog.showViewListener(view -> {
            TextView title = view.findViewById(R.id.cancel_dialog_title);
            title.setText("退款成功,是否打印小票?");
            TextView print = view.findViewById(R.id.cancel_yes);
            TextView cancel = view.findViewById(R.id.cancel_no);
            print.setOnClickListener(v -> {
                print(bean);
            });
            cancel.setOnClickListener(v -> {
                viewDialog.dismiss();
              /*  //退款成功
                Intent intent = new Intent(RefundActivity.this, CollAndInstallDetailActivity.class);
                intent.putExtra("orderId", model.refundBean.get().getOut_trade_no());
                intent.putExtra("needPrint", false);
                startActivity(intent);
                finish();*/
            });
        });
        viewDialog.show(getSupportFragmentManager(), "0");
    }

    //判断是否安装盛付通支付sdk
    private boolean isInstallShengfuPay() {
        PackageManager packageManager = getPackageManager();
        List<PackageInfo> list = packageManager.getInstalledPackages(0);
        for (int i = 0; i < list.size(); i++) {

            if (SystemUtil.getSystemModel().equals("P1") || SystemUtil.getSystemModel().equals("P1_4G") || SystemUtil.getSystemModel().contains("A8")) {
                if (list.get(i).packageName.equalsIgnoreCase("sunmi.fw2.payment.shengpay") ||
                        list.get(i).packageName.equalsIgnoreCase("sunmimi.payment.shengpay") ||
                        list.get(i).packageName.equalsIgnoreCase("com.shengpay.smartpos.shengpaysdk")) {
                    return true;
                }

            }
            Log.d(TAG, "isInstallShengfuPay: 包名：" + list.get(i).packageName);
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        boolean success = false;
        //处理银行卡退款
        if (requestCode == BANK_CODE && data != null) {
            Bundle extras1 = data.getExtras();
            if (extras1 == null) {
                return;
            }
            String payResult = null;//交易结果
            Set<String> keySet = extras1.keySet();
            switch (resultCode) {
                case Activity.RESULT_OK:
                    success = true;
                    Toast.makeText(RefundActivity.this, "交易成功", Toast.LENGTH_SHORT).show();
                    StringBuilder resultBuilder = new StringBuilder();
                    for (String s : keySet) {
                        String str = s + ":" + extras1.getString(s) + ",";
                        resultBuilder.append(str);
                    }
                    Log.d(TAG, "onActivityResult: 支付结果：" + resultBuilder.toString());
                    payResult = resultBuilder.toString();
                    //推送交易结果
                    String content = "银行卡消费撤销成功  ¥" + dataBinding.refundAmount.getText().toString() + " " + getCurrentTime();
                    model.startGt(ISharedPreference.getInstance(getApplication()).getCid(), "天择可付推送提醒", content, () -> {
                    });
                    break;
                case Activity.RESULT_CANCELED:
                    success = false;
                    String reason = data.getStringExtra("reason");
                 //   Log.i("2333",data.getStringExtra("merchantId"));
                    Toast.makeText(RefundActivity.this, reason, Toast.LENGTH_SHORT).show();
                    StringBuilder failBuilder = new StringBuilder();
                    for (String s : keySet) {
                        String str = s + ":" + extras1.getString(s) + ",";
                        failBuilder.append(str);
                    }
                    payResult = failBuilder.toString();
                    break;

            }
            Log.d(TAG, "onActivityResult:payResult :退款交易信息:=============" + payResult);
            //回调上传交易结果
            boolean finalSuccess = success;
            bankViewModel.uploadTradeInfo(payResult, () -> {
                if (finalSuccess) {
                    Intent intent = new Intent(RefundActivity.this, CollAndInstallDetailActivity.class);
                    intent.putExtra("orderId", bankViewModel.bankRefund.get().getOut_trade_no());
                    intent.putExtra("needPrint", true);
                    startActivity(intent);
                    Log.d(TAG, "bankPay: 上传交易信息成功!");
                }
            });
        }
    }

    //获取当前时间
    private String getCurrentTime() {
        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        simpleDateFormat.applyPattern("MM-dd HH:mm:SS");
        return simpleDateFormat.format(new Date());
    }

    //打印内容
    private void print(Object bean) {
        if (bean == null) {
            return;
        }
        List<String> printContent;
        if (bean instanceof RefundBean) {
            printContent = ((RefundBean) bean).getPrint_array();
            Log.d(TAG, "print: 进入打印退款" + printContent);
        } else {
            printContent = ((MsgRefundBean.DataBean) bean).getPrint_array();
        }
        AidlUtil aidlUtil = AidlUtil.getInstance();
        aidlUtil.enterPrinterBuffer(true);
        String bitmapType = printContent.get(0);
        //打印支付方式图标
        commenPrint(printContent, aidlUtil, bitmapType);
//        //打印支付方式图标
//        if (SystemUtil.getSystemModel().contains("A8")) {
//            aidlUtil.printBitmapForA8(bitmapType, 2);
//        } else {
//            int resId = getResId(bitmapType);
//            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
//            aidlUtil.printBitmap(bitmap, "2", "2", resId);
//        }
//        //抬头
//        aidlUtil.printText(printContent.get(1), "32", "32", "1",
//                true, false);
//        aidlUtil.printBlankLine("1", "10");
//        //门店
//        aidlUtil.printText("\n" + printContent.get(2), "24", "24", "1",
//                false, false);
//        aidlUtil.printBlankLine("1", "10");
//        //订单支付方式text开始
//        aidlUtil.printText(printContent.get(3).replace("\\n", "\n"),
//                "24", "24", "0",
//                false, false);
//        //业务记录
//        aidlUtil.printText(printContent.get(4), "32", "32", "0",
//                false, false);
//        //业务记录内容
//        if (!TextUtils.isEmpty(printContent.get(5))) {
//            aidlUtil.printText("\n" + printContent.get(5)
//                            .replace("\\n", "\n"), "24", "24", "0",
//                    false, false);
//        }
//        //退款 ||收款
//        aidlUtil.printText( printContent.get(6), "32", "32", "0",
//                false, false);
//        //退款获取收款内容
//        aidlUtil.printText("\n" + printContent.get(7)
//                        .replace("\\n", "\n"), "24", "24", "0",
//                false, false);
//        //打印二维码
//        aidlUtil.printQr(printContent.get(8), "8", "3");
//        //收银员         //收银员
//        aidlUtil.printText(printContent.get(9).replace("\\n", "\n"),
//                "24", "24", "0", false, false);
//
//        aidlUtil.printBlankLine("1", "10");
//        aidlUtil.printText(printContent.get(10).replace("\\n", "\n"),
//                "24", "24", "1", false, false);
//        aidlUtil.printText(printContent.get(11).replace("\\n", "\n"),
//                "24", "24", "1", false, false);
//        aidlUtil.printText("\n" + printContent.get(12),
//                "24", "24", "1", false, false);
//        aidlUtil.printBlankLine("5", "30");
//        aidlUtil.printCommit();
    }

    @Override
    public void getVerifyCode(TextView target) {

        loginViewModel.getVerCode(ISharedPreference.getInstance(getApplication()).getPhone(), () -> {
//            Toast.makeText(this, "验证码发送成功!", Toast.LENGTH_SHORT).show();
            MCountDownTimer timer = new MCountDownTimer(60 * 1000 + 500, 1000);
            timer.bindView(target);
            timer.start();
        });
    }

    //短信倒计时
    private class MCountDownTimer extends CountDownTimer {
        private TextView timeView;

        private void bindView(TextView timeView) {
            this.timeView = timeView;
        }

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public MCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            timeView.setEnabled(false);
            timeView.setText(String.format("%s  s", millisUntilFinished / 1000));
        }

        @Override
        public void onFinish() {
            timeView.setEnabled(true);
            timeView.setText("验证码");
        }
    }

    @Override
    public void sure() {
        if (dialogFragment == null) {
            return;
        }
        //验证码   退款
        String code = dialogFragment.getCode();
        Log.d(TAG, "sure: 验证码是" + code);
        if (TextUtils.isEmpty(code)) {
            Snackbar.make(dataBinding.rdToolbar, "请输入验证码", Snackbar.LENGTH_SHORT).show();
            return;
        }
        model.startMsgRefund(dataBinding.refundPassword.getText().toString(),
                code, orderId, dataBinding.refundNote.getText().toString(), () -> {
                    //短信退款成功
                    if (dialogFragment != null) {
                        dialogFragment.dismiss();
                    }
                    MsgRefundBean.DataBean dataBean = model.msgRefundBean.get();
                    print(dataBean);
                    showPrintDialog(dataBean);
                    /*Intent intent = new Intent(RefundActivity.this, CollAndInstallDetailActivity.class);
                    intent.putExtra("orderId", Objects.requireNonNull(dataBean).getOut_trade_no());
                    intent.putExtra("needPrint", false);
                    startActivity(intent);
                    finish();*/
                });
    }

    @Override
    public void cancel() {
        if (dialogFragment != null) {
            dialogFragment.dismiss();
        }
    }
}